package com.cqupt.utils;

import com.alibaba.fastjson.JSONArray;
import com.cqupt.pojo.ResponseMessage;
import com.mysql.cj.util.TestUtils;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 转换工具类
 * 格式化到前端的消息
 *
 **/
public class TextUtils {

    /**
     * 替换指定字符串
     *
     * @param dataMap 要操作的Map
     * @param oldString 要被替换的字符串
     * @param newString 要替换成的字符串
     * @param key 要操作的key
     */
    public static void replaceString(Map<String, Object> dataMap, String oldString, String newString, String key){
        String str = (String) dataMap.get(key);
        if (str.contains(oldString)){
            dataMap.put(key, str.replace(oldString, newString));
        }
    }

    /**
     * 从返回的记录中拿到实参
     *
     * @param descOrigin 只有形参的原纪录
     * @param desc api返回的赋了实参的记录
     * @return ArrayList<String> 存储实参
     */
    public static ArrayList<String> getActualValues(String descOrigin, String desc){
        ArrayList<String> valueArray = new ArrayList<>();

        ArrayList<Character> value = new ArrayList<>();

        char[] charsDescOrigin = descOrigin.toCharArray();
        char[] charsDesc = desc.toCharArray();
        int pointerOrigin = 0;     // chars_desc_origin的指针
        int pointer = 0;        // chars_desc的指针
        int lpSize = 0;     // 左括号个数

        try{
            while(pointer <= charsDesc.length-1){
                if (charsDescOrigin[pointerOrigin] != charsDesc[pointer]){
                    // 此时char_desc_origin遍历到了 { 左括号
                    // 操作chars_desc_origin数组的pointer_origin指针
                    while(true){
                        if (charsDescOrigin[pointerOrigin] == '}'){
                            lpSize--;
                            if (lpSize == 0){
                                // 括号关闭
                                break;
                            }
                        } else if (charsDescOrigin[pointerOrigin] == '{'){
                            // 括号开始
                            lpSize++;
                        }
                        pointerOrigin++;
                    }
                    pointerOrigin++;
                    while(charsDesc[pointer] != charsDescOrigin[pointerOrigin]){
                        // 此时开始读取需要的值
                        // 操作chars_desc数组的pointer指针
                        value.add(charsDesc[pointer]);
                        pointer++;
                    }
                    // 两个数组的指针已经再次对齐，将刚才读取的值转为String
                    valueArray.add(value.stream().map(Object::toString).collect(Collectors.joining()));
                    // 清空value数组留待下一次读取值
                    value.clear();
                }
                pointer++;
                pointerOrigin++;
            }
        } catch (IndexOutOfBoundsException e){
            // 出现越界代表两个语句并不匹配，则不翻译
            valueArray.clear();
        }

        return valueArray;
    }

    /**
     * 格式化严重等级severity（从数字到中文）
     *
     * @param dataMap 要格式化的Map
     */
    public static void transformSeverity(Map<String, Object> dataMap, String key) {
        // 后面要将这个放到Properties里
        String[] severity = new String[]{
                "未分类", "信息类", "警告", "一般严重", "严重", "灾难"
        };
        int index = Integer.parseInt((String) dataMap.get(key));
        dataMap.put(key, severity[index]);
    }

    /**
     * 还原严重等级（从中文到数字）
     *
     * @param data 要还原的原中文数据
     * @return 还原后的String[]
     */
    public static String[] revertSeverity(String data) {
        Map<String, String> severities = new HashMap<>();
        severities.put("未分类", "0");
        severities.put("信息类", "1");
        severities.put("警告", "2");
        severities.put("一般严重", "3");
        severities.put("严重", "4");
        severities.put("灾难", "5");

        String[] dataArray = null;
        if (!(data == null || data.isEmpty())){
            // 选择了严重等级
            dataArray = data.split(",");
            for (int i = 0; i < dataArray.length; i++) {
                String temp = severities.get(dataArray[i]);
                dataArray[i] = temp;
            }
        }

        return dataArray;
    }

    /**
     * 格式化问题知晓状态，acknowledged
     *
     * @param dataMap 要格式化的Map
     */
    public static void transformAcknowledged(Map<String, Object> dataMap) {
        String param = "知晓";
        if ( "0".equals(dataMap.get("acknowledged"))) {
            param = "不知晓";
        }
        dataMap.put("acknowledged", param);
    }

    /**
     * 格式化问题时间的类型, source
     *
     * @param dataMap 要格式化的Map
     */
    public static void transformSource(Map<String, Object> dataMap) {
        String param = "内部事件";
        if ("0".equals(dataMap.get("source"))) {
            param = "触发器事件";
        }
        dataMap.put("source", param);
    }

    /**
     * 将连接查询的结果从内层map拿到外层
     *
     * @param dataMap 要操作的数据Map
     * @param key 要拿出来的Map的key
     * @param innerKeys 内部Map要拿出来的value的key
     */
    public static void putInnerValueToOutside(Map<String, Object> dataMap, String key, String[] innerKeys){
        JSONArray jsonArray = (JSONArray) dataMap.get(key);
        if (!jsonArray.isEmpty()){
            Map<String, Object> tempMap = jsonArray.getJSONObject(0);
            for (String s : innerKeys) {
                String tempStr = (String) tempMap.get(s);
                dataMap.put(s, tempStr);
            }
            dataMap.remove(key);
        }
    }

    /**
     * 获取内层Map中的某个值
     * @param dataMap 要操作的数据Map
     * @param key 要进入的内层Map的key
     * @param innerKey 要取出值的key
     * @return innerKey对应的值
     */
    public static Object getInnerValue(Map<String, Object> dataMap, String key, String innerKey){
        Object res = "";
        JSONArray jsonArray = (JSONArray) dataMap.get(key);
        if (!jsonArray.isEmpty()){
            res = jsonArray.getJSONObject(0).get(innerKey);
        }

        return res;
    }

    /**
     * 获取未处理告警项使主机移到外面
     * @param dataMap
     * @param key
     * @param innerKey
     */
    public static void outHost(Map<String, Object> dataMap, String key, String[] innerKey){
        String host = "";
        String hostid = "";
        ArrayList innerValue = new ArrayList();

        JSONArray jsonArray = (JSONArray) dataMap.get(key);
        if (!jsonArray.isEmpty()){
//            for (String s : innerKey) {
//                String tempStr = (String) jsonArray.getJSONObject(0).get(s);
//                dataMap.put(s, tempStr);
//            }
            host = (String) jsonArray.getJSONObject(0).get("host");
            hostid = (String) jsonArray.getJSONObject(0).get("hostid");
        }
        dataMap.put("host", host);
        dataMap.put("hostid", hostid);
        dataMap.remove(key);
    }

    /** 需要查看值映射IF-MIB::ifOperStatus，翻译可能不准确
     * 格式化端口状态，从数字到字符串
     * @param dataMap
     */
    public static void transformPortStatus(Map<String, Object> dataMap,Map<String, Object> returnMap){
        String[] status = new String[]{
                "开启", "关闭","", "未知", "休眠", "不存在", "底层关闭"
        };
        Object lastvalue = dataMap.get("lastvalue");
        if (null != lastvalue) {
            int i = Integer.parseInt(lastvalue.toString());
            if (i == 0){
                returnMap.put("status","未知错误");
            }
            else
                returnMap.put("status", status[i-1]);
        } else {
            returnMap.put("status", status[3]);
        }
    }

    /**
     * @description: 切分name字段用于确定snmp设备的接口数量和接口名
     * @param:
     * @return:
     * @author
     * @date:
     */
    public static List<Map<String, Object>> spiltInterfaceName(List<Map<String, Object>> dataList){
        for (Map<String, Object> dataMap : dataList){
            String name = (String) dataMap.get("name");
            String[] strings = name.split(":");
            dataMap.put("name", strings[0]);
        }

        return dataList;
    }

    /**
     * 将数据封装进ResponseMessage对象
     *
     * @param responseMessage 封装返回消息的对象
     * @param resMap service层返回的Map
     * @return 封装好的返回消息对象
     */
    public static ResponseMessage packDataToResponseMessage(ResponseMessage responseMessage, Map<String, Object> resMap){
        Map<String, Object> resultMap = new HashMap<String, Object>() {{
            put("result", resMap.get("result"));
            put("data_num", resMap.get("dataNum"));
        }};

        responseMessage.setStatus(true);
        responseMessage.setContent(resultMap);

        return responseMessage;
    }

    /**
     * 封装count结果进ResponseMessage对象
     *
     * @param responseMessage 封装返回消息的对象
     * @param resStrArray 统计结果
     * @return 封装好的返回消息对象
     */
    public static ResponseMessage packCountToResponseMessage(ResponseMessage responseMessage, String[] resStrArray){
        Map<String, Object> resultMap = new HashMap<String, Object>() {{
            put("result", resStrArray);
        }};

        responseMessage.setStatus(true);
        responseMessage.setContent(resultMap);

        return responseMessage;
    }

    /**
     * 将消息list和总条数int封装到map
     *
     * @param dataList 要封装的消息list
     * @param dataTotalNum 要封装的总条数int
     * @return result(消息list)，dataNum(总条数int)
     */
    public static Map<String, Object> packDataToMap(List<Map<String, Object>> dataList, int dataTotalNum){
        Map<String, Object> resMap = new HashMap<String, Object>(){{
            put("result", dataList);
            put("dataNum", dataTotalNum);
        }};

        return resMap;
    }


    /**
     * 读取test.txt的数据装换成map
     * @return
     */
    public static HashMap<String,String> getDataToMap(){
        InputStreamReader reader = null;
        HashMap<String, String> itemMap = new HashMap<>();
        try {
            reader = new InputStreamReader(new FileInputStream(TestUtils.class.getResource("/itemChinese.txt").getPath()),"utf-8");
            BufferedReader bufferedReader = new BufferedReader(reader);
            String tempString = null;

            while ((tempString = bufferedReader.readLine()) != null) {
              //  System.out.println(tempString);
                String[] split = tempString.split("\\|");
             //   System.out.println("-----------");
//                System.out.println(split[1]);
                itemMap.put(split[0],split[1]);
            }
            reader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return itemMap;
    }
    /**
    * @Description //新增翻译字段
    * @Date 14:47 2021/3/1
    * @Param [data]翻译字段
    **/
    public static void writeFile(String data){
        String writeToPath=TextUtils.class.getResource("/itemChinese.txt").getPath();
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(new File(writeToPath),true);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,"utf-8");
            outputStreamWriter.write(data+"\n");
            outputStreamWriter.close();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /*
     * @Description //针对于触发器的汉化翻译
     * @Date 14:47 2021/4/1
     * */
    public static HashMap<String,String> getTriggerDataToMap(){
        InputStreamReader reader = null;
        HashMap<String, String> triggerMap = new HashMap<>();
        try {
            reader = new InputStreamReader(new FileInputStream(TestUtils.class.getResource("/triggerChinese.txt").getPath()),"utf-8");
            BufferedReader bufferedReader = new BufferedReader(reader);
            String tempString = null;
            while ((tempString = bufferedReader.readLine()) != null) {
                String[] split = tempString.split("\\|");
                triggerMap.put(split[0], split[1]);
            }
            reader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return triggerMap;
    }

    /**
     *  读入模板配置文件，输出关于配置文件的字符串
     */
    public static String getTemplateXML(String filePath){

        BufferedReader br = null;
        StringBuilder stringBuffer = new StringBuilder(100);
        try {
            // 字节输入流
            FileInputStream fis = new FileInputStream(filePath);
            // 转换流
            InputStreamReader reader = new InputStreamReader(fis);
            br = new BufferedReader(reader);

            String data;
            while((data=br.readLine())!=null){
                // 去除前后空格
                data = data.trim();
                stringBuffer.append(data);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuffer.toString();
    }
}
